package com.hx.vending.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.EquipmentTypeCaseResult;
import com.hx.vending.bean.entity.EquipmentTypeRiseResult;
import com.hx.vending.dao.*;
import com.hx.vending.mqtt.RunnerSendMqtt;
import com.hx.vending.service.IModelService;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2018/11/26.
 * 模板
 */
@Service
public class ModelServiceImpl implements IModelService {

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private ModelTrailsMapper modelTrailsMapper;

    @Autowired
    private RiseMapper riseMapper;

    @Autowired
    private TrailsMapper trailsMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private EquipmentTypeRiseMapper equipmentTypeRiseMapper;

    @Autowired
    private EquipmentTypeMapper equipmentTypeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private EquipmentTypeCaseMapper equipmentTypeCaseMapper;


    /**
     * 添加模板信息
     * @param userId           商户id
     * @param model            模板信息
     * @return
     */
    public Msg insertModel(Integer userId, Model model){
        if(ToolUtil.isNotEmpty(model) && ToolUtil.isNotEmpty(userId) && ToolUtil.isNotEmpty(model.getModelType())){
            //设置用户id
            model.setModelUserId(userId);
            //查询是否已经存在
            List<Model> checkModel = this.modelMapper.selectByExampleSelective(model);
            if (checkModel.size() > 1) {
                return Msg.fail().add("msg", "该模板已存在!!");
            }
            //保存模板信息
            int resultinsert = this.modelMapper.insertSelective(model);
            if(0 != resultinsert){

                //查出刚添加的模板
                Model selectModel = this.modelMapper.selectByPrimaryKeySelective(model);

//                //根据选择的设备类型id查询货道
//                EquipmentTypeTrails equipmentTypeTrails = new EquipmentTypeTrails();
//                equipmentTypeTrails

                //查出模板类型
                EquipmentTypeRise equipmentTypeRise = new EquipmentTypeRise();
                //equipmentTypeRise.setEquipmentTypeId(model.getModelType());
                List<EquipmentTypeRise> equipmentTypeRises = this.equipmentTypeRiseMapper.selectByExampleSelective(equipmentTypeRise);

                if (ToolUtil.isNotEmpty(equipmentTypeRises)) {
                    //得到每层的货道数保存模板的层和货道信息
                    for (int i = 0; i < equipmentTypeRises.size(); i++) {
                        //添加层信息
                        Rise rise = new Rise();
                        rise.setRiseNumber(equipmentTypeRises.get(i).getEquipmentTypeRise());
                        rise.setRiseModelId(selectModel.getModelId());
                        int insertRise = this.riseMapper.insertSelective(rise);

                        if (insertRise != 0) {
                            //查出刚添加的层信息
                            Rise selectRise = this.riseMapper.selectByPrimaryKeySelective(rise);

                            int size = equipmentTypeRises.get(i).getEquipmentTypeRiseTrails();
                            for (int j = 0; j < size; j++) {
                                //添加货道信息
                                Trails trails = new Trails();
                                Integer trailsNumber = j+1;
                                trails.setTrailsNumber(equipmentTypeRises.get(i).getEquipmentTypeRise() + "-" + trailsNumber);
                                trails.setTrailsRiseId(selectRise.getRiseId());
                                //trails.setTrailsGoodsCapacity(equipmentTypeRises.get(i).getEquipmentTypeTrailsCapacity());
                                //货道位置
                                String ceng = i + "";
                                String lie = j + "";
                                if (ceng.length() == 1) {
                                    ceng = "0" + i;
                                }
                                if (lie.length() == 1) {
                                    lie = "0" + j;
                                }
                                trails.setTrailsPosition(ceng + lie);
                                int insertTrails = this.trailsMapper.insertSelective(trails);

                                if (insertTrails != 0) {
                                    //查出刚添加的货道的信息
                                    Trails selectTrails = this.trailsMapper.selectByPrimaryKeySelective(trails);
                                    //添加模板关联信息
                                    ModelTrails ModelTrails = new ModelTrails();
                                    //模板id
                                    ModelTrails.setModelTrailsModelId(selectModel.getModelId());
                                    //层id
                                    ModelTrails.setModelTrailsRiseId(selectRise.getRiseId());
                                    //货道id
                                    ModelTrails.setModelTrailsTrailsId(selectTrails.getTrailsId());
                                    //添加关联信息
                                    this.modelTrailsMapper.insertSelective(ModelTrails);
                                }
                            }
                        }
                    }
                }
                return Msg.success();
            }else {
                return Msg.fail();
            }
        }else{
            return Msg.fail().add("msg", "请输入正确的信息");
        }
    }


    /**
     * 修改模板信息
     * @param model
     * @return
     */
    public Msg updateModel(Model model){
        if(ToolUtil.isNotEmpty(model)){
            int resultupdate=this.modelMapper.updateByPrimaryKeySelective(model);
            if(resultupdate != 0){
                return Msg.success();
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }
    }

    /**
     * 删除模板信息
     * @param modelId 模板id
     * @return Msg
     */
    public Msg deleteModel(Integer modelId){
        if (ToolUtil.isNotEmpty(modelId)){
            //删除模板信息
            int deleteModel = this.modelMapper.deleteByPrimaryKey(modelId);
            //删除模板信息后，删除模板关联的信息
            if(deleteModel != 0){
                //查询模板关联信息
                ModelTrails modelTrails = new ModelTrails();
                modelTrails.setModelTrailsModelId(modelId);
                List<ModelTrails> modelTrailsList = this.modelTrailsMapper.selectByExampleSelective(modelTrails);
                if(ToolUtil.isNotEmpty(modelTrailsList)){
                    for (ModelTrails modeltrails:modelTrailsList) {
                        //删除模板层信息
                        this.riseMapper.deleteByPrimaryKey(modeltrails.getModelTrailsRiseId());
                        //删除货道信息
                        this.trailsMapper.deleteByPrimaryKey(modeltrails.getModelTrailsTrailsId());
                        //删除模板关联
                        this.modelTrailsMapper.deleteByPrimaryKey(modeltrails.getModelTrailsId());
                    }
                }
            }else{
                return Msg.fail().add("msg", "模板信息删除失败");
            }
        }else{
            return Msg.fail().add("msg", "模板id不能为空");
        }
        return Msg.success();
    }


    /**
     * 查询模板/设备所有货道信息
     * @param model
     * @return
     */
    public Msg selectAllModelOrEquiMessage(Model model, String equipmentId) {

        if (ToolUtil.isNotEmpty(model) && ToolUtil.isEmpty(equipmentId)) {
            //如果模板信息不为空，设备id为空，查询模板的信息

            //模板信息
            List<Model> modelList = modelMapper.selectByExampleSelective(model);

            if (ToolUtil.isNotEmpty(modelList)) {

                for (Model formodel: modelList) {

                    //根据模板id查询层信息
                    Rise rise = new Rise();
                    rise.setRiseModelId(formodel.getModelId());
                    List<Rise> riseList = this.riseMapper.selectByExampleSelective(rise);

                    if (ToolUtil.isNotEmpty(riseList)) {

                        for (Rise forrise: riseList) {

                            //模板关联信息
                            ModelTrails modelTrails = new ModelTrails();
                            modelTrails.setModelTrailsModelId(formodel.getModelId());//模板id
                            modelTrails.setModelTrailsRiseId(forrise.getRiseId());//层id
                            List<ModelTrails> modelTrailsList = this.modelTrailsMapper.selectByExampleSelective(modelTrails);

                            if (ToolUtil.isNotEmpty(modelTrailsList)) {

                                List<TrailsGoods> trailsGoodsList = new ArrayList<TrailsGoods>();

                                for (ModelTrails modeltrails: modelTrailsList) {

                                    //货道信息和商品信息
                                    Trails trails = new Trails();
                                    trails.setTrailsId(modeltrails.getModelTrailsTrailsId());
                                    List<TrailsGoods> selectTrailsGoodsList = this.trailsMapper.selectTrailsAndGoods(trails);

                                    trailsGoodsList.add(selectTrailsGoodsList.get(0));
                                }
                                forrise.setTrailsGoodsList(trailsGoodsList);
                            }
                        }
                        formodel.setRise(riseList);
                    }
                }

                return Msg.success().add("modelAllMessage", modelList);

            }else{
                return Msg.fail().add("msg", "没用当前模板");
            }

        }else if (ToolUtil.isNotEmpty(equipmentId)) {
            //如果模板信息为空，设备id不为空，查询设备的信息

            List<Object> equipmentAllCaseList = new ArrayList<Object>();

            //根据设备id查询该设备的机箱数量
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
            if (ToolUtil.isNotEmpty(selectEquipment)) {

                //查询机箱分组
                List<Trails> trailsCaseList = this.trailsMapper.selectCaseGroupBy(equipmentId);

                if (ToolUtil.isNotEmpty(trailsCaseList)) {
                    for (Trails caseNumber: trailsCaseList) {

                        List<Object> equipmentCaseList = new ArrayList<Object>();
                        EquipmentTypeCaseResult equipmentTypeCaseResult = new EquipmentTypeCaseResult();

                        //查询层分组
                        List<Trails> trailsRiseList = this.trailsMapper.selectRiseGroupBy(caseNumber.getTrailsCaseId(), equipmentId);

                        if (ToolUtil.isNotEmpty(trailsRiseList)) {
                            for (Trails riseNumber:trailsRiseList) {

                                //查询货道信息
                                Trails trails = new Trails();
                                trails.setTrailsRiseId(riseNumber.getTrailsRiseId());
                                trails.setTrailsCaseId(caseNumber.getTrailsCaseId());
                                trails.setTrailsEquipmentId(equipmentId);
                                List<TrailsGoods> selectTrailsGoodsList = this.trailsMapper.selectTrailsAndGoods(trails);

                                //保存每个机箱每层的货道信息
                                EquipmentTypeRiseResult equipmentRiseList = new EquipmentTypeRiseResult();
                                equipmentRiseList.setRiseNumber(riseNumber.getTrailsRiseId().toString());
                                equipmentRiseList.setRiseList(selectTrailsGoodsList);
                                //保存每个机箱的信息
                                equipmentCaseList.add(equipmentRiseList);
                            }
                            //保存所有机箱的货道信息
                            equipmentTypeCaseResult.setCaseNumber(caseNumber.getTrailsCaseId());
                            equipmentTypeCaseResult.setCaseList(equipmentCaseList);
                            equipmentAllCaseList.add(equipmentTypeCaseResult);
                        }
                    }
                }
                return Msg.success().add("equipmentAllCaseList", equipmentAllCaseList);
            }else {
                return Msg.fail().add("msg", "该设备不存在");
            }
        }
        return Msg.fail();
    }

    /**
     * 查询该用户下的模板列表
     * @param userId        用户id
     * @param pn            页码
     * @param model         模板查询条件
     * @return
     */
    public Msg selectModelList(Integer userId, Integer pn, Model model, String equipmentId) {

        if(ToolUtil.isNotEmpty(userId)){

            //如果设备id不为空，要根据设备的类型查询模板
            if (ToolUtil.isNotEmpty(equipmentId)) {
                Equipment equipment = new Equipment();
                equipment.setEquipmentId(equipmentId);
                Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
                if (ToolUtil.isNotEmpty(selectEquipment)) {
                    model.setModelType(Integer.parseInt(selectEquipment.getEquipmentType()));
                }
            }

            //分页
            PageHelper.startPage(pn, 10);
            //查出模板信息
            model.setModelUserId(userId);
            List<Model> modelList = this.modelMapper.selectByExampleSelective(model);
            if(ToolUtil.isNotEmpty(modelList)){
                for (Model forModel: modelList) {

                    //层数
                    Integer rise = 0;
                    //货道数
                    Integer trails = 0;

                    //查出模板关联信息
                    ModelTrails modelTrails = new ModelTrails();
                    modelTrails.setModelTrailsModelId(forModel.getModelId());
                    List<ModelTrails> modelTrailsList = this.modelTrailsMapper.selectByExampleSelective(modelTrails);
                    if (ToolUtil.isNotEmpty(modelTrailsList)) {
                        trails = modelTrailsList.size();

                        //记录层数
                        Set<Integer> riseSet = new HashSet<Integer>();
                        for (ModelTrails forModelTrails: modelTrailsList) {
                            riseSet.add(forModelTrails.getModelTrailsRiseId());
                        }
                        rise = riseSet.size();
                    }

                    forModel.setRiseNumber(rise);
                    forModel.setTrailsNumber(trails);

                    //查询设备类型名称
                    if (ToolUtil.isNotEmpty(forModel.getModelType())) {
                        EquipmentType equipmentType = new EquipmentType();
                        equipmentType.setEquipmentTypeId(forModel.getModelType());
                        EquipmentType selectEquipmentType = this.equipmentTypeMapper.selectByPrimaryKeySelective(equipmentType);
                        if (ToolUtil.isNotEmpty(selectEquipmentType)) {
                            forModel.setEquipmentTypeName(selectEquipmentType.getEquipmentTypeName());
                        }
                    }
                }
            }

            PageInfo page = new PageInfo(modelList, 5);
            return Msg.success().add("pageInfo", page);
        }else{
            return Msg.fail().add("msg", "用户id为空");
        }
    }


    /**
     * 将模板应用到设备
     * @param modelId
     * @param equipmentId
     * @return
     */
    public Msg insertEquipmentByModel(Integer modelId, String equipmentId) {

        if (ToolUtil.isNotEmpty(modelId) && ToolUtil.isNotEmpty(equipmentId)) {

            //查询设备的信息
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipent = this.equipmentMapper.selectByPrimary(equipment);
            //查询模板信息
            Model model = new Model();
            model.setModelId(modelId);
            Model selectModel = this.modelMapper.selectByPrimaryKeySelective(model);

            if (!selectEquipent.getEquipmentType().equals(selectModel.getModelType().toString())) {
                return Msg.fail().add("msg", "模板与该设备类型不匹配!!");
            }

            //将模板的商品信息保存到设备的货道
            //查询设备的货道
            Trails equipmentTrails = new Trails();
            equipmentTrails.setTrailsEquipmentId(equipmentId);
            List<Trails> equipmentTrailsList = this.trailsMapper.selectByExampleSelective(equipmentTrails);
            //查询模板的层
            Rise rise = new Rise();
            rise.setRiseModelId(modelId);
            List<Rise> riseList = this.riseMapper.selectByExampleSelective(rise);

            if (ToolUtil.isNotEmpty(equipmentTrailsList) && ToolUtil.isNotEmpty(riseList)) {
                for (Rise forRise: riseList) {
                    Trails riseTrails = new Trails();
                    riseTrails.setTrailsRiseId(forRise.getRiseId());
                    List<Trails> selectRiseTrails = this.trailsMapper.selectByExample(riseTrails);
                    for (Trails forSelectRiseTrails: selectRiseTrails) {
                        for (Trails equiTrails: equipmentTrailsList) {
                            if (forSelectRiseTrails.getTrailsPosition().equals(equiTrails.getTrailsPosition())) {
                                equiTrails.setTrailsGoodsId(forSelectRiseTrails.getTrailsGoodsId());
                                this.trailsMapper.updateByPrimaryKeySelective(equiTrails);
                                break;
                            }
                        }
                    }
                }
            }

            //保存设备应用的模板id
            equipment.setEquipmentModelId(modelId);
            this.equipmentMapper.updateByPrimaryKeySelective(equipment);

            //发送mqtt消息更新设备的信息
            String fourNumber = ToolUtil.generateNonceStr(4);//随机数
            RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
            runnerSendMqtt.setMessage(equipmentId + "," + fourNumber);
            runnerSendMqtt.setRedisTemplate(redisTemplate);
            runnerSendMqtt.setTheme("RefreshGoods");
            runnerSendMqtt.setThreadName("刷新货道库存指令");
            runnerSendMqtt.setRedisKey("RefreshGoods-" + equipmentId);
            runnerSendMqtt.start();

            return Msg.success();
        }else {
            return Msg.fail();
        }
    }


}
